package com.whisper.common.core.interceptor;

import com.whisper.common.annotation.PageQuery;
import com.whisper.common.core.domain.AjaxResult;
import com.whisper.common.core.domain.ExceptionResult;
import com.whisper.common.utils.PageUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class GlobalResultInterceptor implements ResponseBodyAdvice<Object> {
	
    private PageUtils pageUtils = new PageUtils();

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter methodParameter, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 统一全局异常处理
        if ((body instanceof ExceptionResult) || (body instanceof String)) return body;
        
        // 此处的 Result 对象是我自定义的返回值类型,具体根据自己需求修改即可
        PageQuery annotation = methodParameter.getMethodAnnotation(PageQuery.class);
        if (!ObjectUtils.isEmpty(annotation)) {
            return pageUtils.startPage(body, annotation);
        }
        
        // 这里可以对返回值进行修改二次封装等操作
        return AjaxResult.success(body);
    }

}
